<template>
  <div class="main">
    <a-card
      :bordered="false"
      style="width: 420px; float: right; padding: 24px 40px; box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.05)"
    >
      <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
        <a-tabs
          :activeKey="customActiveKey"
          :tabBarStyle="{ textAlign: 'center', fontWeight: '400' }"
          @change="handleTabClick"
          v-if="routePath == 'mchLogin'"
        >
          <a-tab-pane key="tab1" tab="密码登录">
            <div class="pw_login">
              <span class="pw_login_title">账号登录</span>
              <img
                :src="
                  !loginType ? require('@/assets/images/login/qrcode.png') : require('@/assets/images/login/pc.png')
                "
                class="qrcode"
                @click="
                  () => {
                    this.loginType = !this.loginType
                  }
                "
              />
              <span class="pw_login_type">{{ !loginType ? '扫码登录' : '密码登录' }}</span>
            </div>
            <div v-if="!loginType">
              <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px" :message="loginError" />
              <a-form-item>
                <a-input
                  size="large"
                  type="text"
                  placeholder="用户名或邮箱"
                  v-decorator="[
                    'username',
                    {
                      rules: [
                        { required: true, message: '请输入帐户名或邮箱地址' },
                        { validator: handleUsernameOrEmail }
                      ],
                      validateTrigger: 'change'
                    }
                  ]"
                >
                  <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input>
              </a-form-item>
              <a-form-item>
                <a-input-password
                  size="large"
                  type="password"
                  autocomplete="false"
                  placeholder="密码"
                  v-decorator="[
                    'password',
                    { rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur' }
                  ]"
                >
                  <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </a-input-password>
              </a-form-item>
            </div>
            <div v-else style="text-align: center">
              <img src="@/assets/images/login/qrcode.png" style="width: 134px" />
              <div class="qr_desc">
                请使用<span style="color: black">微信扫码</span>或<span style="color: black">App</span>扫码登录
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane key="tab2" tab="短信码登录">
            <div class="pw_login">
              <span class="pw_login_title">手机号登录</span>
            </div>
            <a-form-item>
              <a-input
                size="large"
                type="text"
                placeholder="手机号"
                v-decorator="[
                  'mobile',
                  {
                    rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }],
                    validateTrigger: 'change'
                  }
                ]"
              >
                <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>

            <a-row :gutter="16">
              <a-col class="gutter-row" :span="15">
                <a-form-item>
                  <a-input
                    size="large"
                    type="text"
                    placeholder="验证码"
                    v-decorator="[
                      'captcha',
                      { rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur' }
                    ]"
                  >
                    <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="9">
                <a-button
                  class="getCaptcha"
                  tabindex="-1"
                  :disabled="state.smsSendBtn"
                  @click.stop.prevent="getCaptcha"
                  v-text="(!state.smsSendBtn && '获取验证码') || state.time + ' s'"
                ></a-button>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
        <div v-else>
          <div class="pw_login">
            <span class="pw_login_title">账号登录</span>
          </div>
          <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px" :message="loginError" />
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="用户名或邮箱"
              v-decorator="[
                'username',
                {
                  rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }],
                  validateTrigger: 'change'
                }
              ]"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input-password
              size="large"
              type="password"
              autocomplete="false"
              placeholder="密码"
              v-decorator="[
                'password',
                { rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur' }
              ]"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input-password>
          </a-form-item>
        </div>
        <a-form-item v-if="!loginType">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="state.loginBtn"
            :disabled="state.loginBtn"
            >登录</a-button
          >
        </a-form-item>
        <a-form-item v-if="false">
          <a-checkbox v-decorator="['rememberMe', { valuePropName: 'checked' }]">下次自动登录</a-checkbox>
          <!-- <router-link :to="{ name: 'recover', params: { user: 'aaa' } }" class="forge-password" style="float: right"
            >忘记密码</router-link
          > -->
        </a-form-item>
        <a-divider></a-divider>
        <!-- <div style="font-size: 12px; color: #aaaaaa">温馨提示：产品通用</div> -->
        <div class="user-login-other" v-if="false">
          <span>其他登录方式</span>
          <a>
            <a-icon class="item-icon" type="alipay-circle"></a-icon>
          </a>
          <a>
            <a-icon class="item-icon" type="taobao-circle"></a-icon>
          </a>
          <a>
            <a-icon class="item-icon" type="weibo-circle"></a-icon>
          </a>
          <router-link class="register" :to="{ name: 'register' }">注册账户</router-link>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getSmsCaptcha } from '@/api/login'
import storage from 'store'
import router from '@/router'
import store from '@/store'

export default {
  components: {},
  data() {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      loginError: '账号或密码错误',
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created() {
    // 为了避免登陆后数据混乱，先清除一些缓存
    storage.remove('isSaas')
    storage.remove('isSaasStore')
    storage.remove('isSaasMd')
    storage.remove('mdId')
    storage.remove('storeId')
    storage.remove('isPlatform')
    storage.remove('isSupplier')
    storage.remove('currentStoreUsername')
    console.log('清理数据完成')
  },

  computed: {
    routePath() {
      return this.$route.name
    }
  },

  watch: {
    customActiveKey(val) {
      console.log(this.$store)
      this.$store.commit('SET_LOGINTYPE', val)
    }
  },

  methods: {
    ...mapActions(['Login', 'Logout', 'GenerateRoutes', 'GetInfo']),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          if (customActiveKey === 'tab1') {
            loginParams[!state.loginType ? 'email' : 'username'] = values.username
            loginParams.password = values.password
            loginParams.loginType = !state.loginType ? 'email' : 'username'
          }
          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.data.captcha,
                duration: 8
              })
            })
            .catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    getHashValue(queryName) {
      var reg = new RegExp('(^|&)' + queryName + '=([^&]*)(&|$)', 'i')
      var r = window.location.hash.substr(1).match(reg)
      if (r != null) {
        return decodeURI(r[2])
      } else {
        return null
      }
    },
    afterLoginRedirect() {
      try {
        if (this.$route.query) {
          const query = this.$route.query
          if (query.redirect && query.redirect.indexOf('http') > -1) {
            const from = this.getHashValue('from')
            if (from == 'diyAdmin') {
              window.location.href = query.redirect
              console.log(query.redirect)
            } else {
              window.location.href = query.redirect
            }
          }
          if (query.redirect && query.redirect.indexOf('http') <= -1) {
            this.$router.push({ path: query.redirect })
          }
        }
      } catch (err) {
        console.log(err)
      }
    },

    getRoute(fn) {
      this.GetInfo()
        .then(res => {
          const roles = res.data && res.data.role
          // generate dynamic router
          this.GenerateRoutes({ roles }).then(() => {
            // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表
            // 动态替换redirect,防止没有权限
            const routers = store.getters.addRouters
            for (let i = 0; i < routers.length; i++) {
              if (routers[i]?.redirect && routers[i].redirect == '/dashboard') {
                for (let ii = 0; ii < routers[i].children.length; ii++) {
                  const child = []
                  for (let iii = 0; iii < routers[i].children[ii].children.length; iii++) {
                    child.push(routers[i].children[ii].children[iii].path)
                  }
                  if (routers[i].children[ii].redirect) {
                    if (child.indexOf(routers[i].children[ii].redirect) === -1) {
                      routers[i].children[ii].redirect = child[0]
                    }
                  }
                }
              }
            }

            // console.log('router.addRoutes,',router.addRoutes);
            router.addRoutes(store.getters.addRouters)

            // console.log('localStorage.getItem(isDandianpu)',localStorage.getItem('isDandianpu'));
            // console.log('localStorage.getItem(isDandianpu)',localStorage.getItem('isDandianpu'));

            // if(localStorage.getItem('isDandianpu') === 'true'){
            //   this.$router.push({ path : '/statistic/goods'})
            // }else{
            //   this.$router.push({ name:routers[0].children[0].name})
            // }

            this.$router.push({ name: routers[0].children[0].name })

            // this.$router.push({ path })
            // // 延迟 1 秒显示欢迎信息
            // setTimeout(() => {
            //   this.$notification.success({
            //     message: '欢迎',
            //     description: `${timeFix()}，欢迎回来`
            //   })
            // }, 1000)
            // this.isLoginError = false

            // let { query } = this.$route
            // // console.log('query,', query)
            // if ((query && query.redirect === '/') || !query.redirect) {
            //   let path = store.getters.addRouters[0].children[0].path
            //   this.$router.push({ path })
            //   return
            // }

            // fn()
          })
        })
        .catch(() => {
          this.$message.error('请求用户信息失败，请重试')

          // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
          this.stepCaptchaCancel()
        })
    },

    loginSuccess(res) {
      this.getRoute(() => {
        this.afterLoginRedirect(res)
      })
    },
    requestFailed(err) {
      this.isLoginError = true
      if (err.msg) {
        this.loginError = err.msg
      }
    }
  }
}
</script>

<style lang="less" scoped>
.qr_desc {
  margin-top: 16px;
  text-align: center;
  width: 100%;
  font-size: 12px;
}
.pw_login {
  margin: 0 0 33px 0;
  .pw_login_title {
    font-size: 16px;
    color: black;
    line-height: 34px;
  }
  .pw_login_type {
    width: 82px;
    display: block;
    background: #f5f5f5;
    float: right;
    font-size: 12px;
    padding: 8px 13px;
    position: relative;
    &::after {
      content: '';
      position: absolute;
      right: -8px;
      top: 50%;
      width: 10px;
      height: 10px;
      background: #f5f5f5;
      transform: rotate(-45deg) translateY(-50%);
    }
  }
  .qrcode {
    margin-top: 5px;
    float: right;
    width: 24px;
    margin-left: 10px;
    cursor: pointer;
  }
}
/deep/.ant-tabs-nav .ant-tabs-tab {
  font-size: 18px;
  padding-bottom: 24px;
}
/deep/.ant-tabs-nav .ant-tabs-tab-active {
  color: rgba(36, 104, 242, 1);
  font-weight: 400;
}
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    border-radius: 20px;
    background: rgba(42, 108, 236, 1);
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    font-weight: 500;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
